home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Developer Essentials / DTS Sample Code / Macintosh Sample Code / SC.001.Sample / Sample.p < prev    next >
Encoding:
Text File  |  1989-05-31  |  31.7 KB  |  907 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #
  20. #    Components:
  21. #                Sample.p            June 1, 1989
  22. #                Sample.c            June 1, 1989
  23. #                Sample.a            June 1, 1989
  24. #                Sample.inc1.a        June 1, 1989
  25. #                SampleMisc.a        June 1, 1989
  26. #                Sample.r            June 1, 1989
  27. #                Sample.h            June 1, 1989
  28. #                PSample.make        June 1, 1989
  29. #                CSample.make        June 1, 1989
  30. #                ASample.make        June 1, 1989
  31. #
  32. #    Sample is an example application that demonstrates how to
  33. #    initialize the commonly used toolbox managers, operate 
  34. #    successfully under MultiFinder, handle desk accessories, 
  35. #    and create, grow, and zoom windows.
  36. #
  37. #    It does not by any means demonstrate all the techniques 
  38. #    you need for a large application. In particular, Sample 
  39. #    does not cover exception handling, multiple windows/documents, 
  40. #    sophisticated memory management, printing, or undo. All of 
  41. #    these are vital parts of a normal full-sized application.
  42. #
  43. #    This application is an example of the form of a Macintosh 
  44. #    application; it is NOT a template. It is NOT intended to be 
  45. #    used as a foundation for the next world-class, best-selling, 
  46. #    600K application. A stick figure drawing of the human body may 
  47. #    be a good example of the form for a painting, but that does not 
  48. #    mean it should be used as the basis for the next Mona Lisa.
  49. #
  50. #    We recommend that you review this program or TESample before 
  51. #    beginning a new application.
  52. #
  53. ------------------------------------------------------------------------------}
  54.  
  55.  
  56. PROGRAM Sample;
  57.  
  58.  
  59. {Segmentation strategy:
  60.  
  61.  This program consists of three segments. Main contains most of the code,
  62.  including the MPW libraries, and the main program. Initialize contains
  63.  code that is only used once, during startup, and can be unloaded after the
  64.  program starts. %A5Init is automatically created by the Linker to initialize
  65.  globals for the MPW libraries and is unloaded right away.}
  66.  
  67.  
  68. {SetPort strategy:
  69.  
  70.  Toolbox routines do not change the current port. In spite of this, in this
  71.  program we use a strategy of calling SetPort whenever we want to draw or
  72.  make calls which depend on the current port. This makes us less vulnerable
  73.  to bugs in other software which might alter the current port (such as the
  74.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  75.  Hopefully, this also makes the routines from this program more self-contained,
  76.  since they don't depend on the current port setting.}
  77.  
  78.  
  79. USES
  80.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps;
  81.  
  82. CONST
  83.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  84.      These constants are from that file.}
  85.     {1.02 - since using MPW 3.0 only, we include Traps.p, so we now have trap numbers.}
  86.  
  87.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  88.     {SysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  89.      SysEnvRec we understand.}
  90.     kSysEnvironsVersion        = 1;
  91.  
  92.     {OSEvent is the event number of the suspend/resume and mouse-moved events sent
  93.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  94.      high byte of the message sent to determine which kind it is. To differentiate
  95.      suspend and resume events we check the resumeMask bit.}
  96.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  97.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  98.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  99.     kNoEvents                = 0;        {no events mask}
  100.  
  101.     {1.01 - kMinHeap - This is the minimum result from the following
  102.      equation:
  103.             
  104.             ORD(GetApplLimit) - ORD(ApplicZone)
  105.             
  106.      for the application to run. It will insure that enough memory will
  107.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  108.      application, and still give the application some 'breathing room'.
  109.      To derive this number, we ran under a MultiFinder partition that was
  110.      our requested minimum size, as given in the 'SIZE' resource.}
  111.      
  112.     kMinHeap    = 21 * 1024;
  113.     
  114.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  115.      at initialization time, for the application to run. This number acts
  116.      as a double-check to insure that there really is enough memory for the
  117.      application to run, including what has been taken up already by
  118.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  119.      
  120.     kMinSpace    = 8 * 1024;
  121.     
  122.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  123.     kExtremeNeg    = -32768;
  124.     kExtremePos    = 32767 - 1;            {required for old region bug}
  125.     
  126.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  127.     rMenuBar    = 128;                    {application's menu bar}
  128.     rAboutAlert    = 128;                    {about alert}
  129.     rUserAlert    = 129;                    {error user alert}
  130.     rWindow        = 128;                    {application's window}
  131.     rStopRect    = 128;                    {rectangle for Stop light}
  132.     rGoRect        = 129;                    {rectangle for Go light}
  133.  
  134.     {The following constants are used to identify menus and their items. The menu IDs
  135.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  136.     mApple        = 128;                    {Apple menu}
  137.     iAbout        = 1;
  138.  
  139.     mFile        = 129;                    {File menu}
  140.     iNew        = 1;
  141.     iClose        = 4;
  142.     iQuit        = 12;
  143.  
  144.     mEdit        = 130;                    {Edit menu}
  145.     iUndo        = 1;
  146.     iCut        = 3;
  147.     iCopy        = 4;
  148.     iPaste        = 5;
  149.     iClear        = 6;
  150.  
  151.     mLight        = 131;                    {Light menu}
  152.     iStop        = 1;
  153.     iGo            = 2;
  154.     
  155.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  156.     kDITop        = $0050;
  157.     kDILeft        = $0070;
  158.  
  159.  
  160. VAR
  161.     {The "g" prefix is used to emphasize that a variable is global.}
  162.  
  163.     {GMac is used to hold the result of a SysEnvirons call. This makes
  164.      it convenient for any routine to check the environment. It is
  165.      global information, anyway.}
  166.     gMac                : SysEnvRec;    {set up by Initialize}
  167.  
  168.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  169.      trap is available. If it is false, we know that we must call GetNextEvent.}
  170.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  171.  
  172.     {GInBackground is maintained by our osEvent handling routines. Any part of
  173.      the program can check it to find out if it is currently in the background.}
  174.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  175.  
  176.  
  177.     {The following globals are the state of the window. If we supported more than
  178.      one window, they would be attatched to each document, rather than globals.}
  179.  
  180.     {GStopped tells whether the stop light is currently on stop or go.}
  181.     gStopped            : BOOLEAN;        {maintained by Initialize and SetLight}
  182.  
  183.     {GStopRect and gGoRect are the rectangles of the two stop lights in the window.}
  184.     gStopRect            : Rect;            {set up by Initialize}
  185.     gGoRect                : Rect;            {set up by Initialize}
  186.  
  187.  
  188. {$S Initialize}
  189. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  190.  
  191. {Check to see if a given trap is implemented. This is only used by the
  192.  Initialize routine in this program, so we put it in the Initialize segment.
  193.  The recommended approach to see if a trap is implemented is to see if
  194.  the address of the trap routine is the same as the address of the
  195.  Unimplemented trap.}
  196. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  197.  if a ToolTrap is out of range of a pre-MacII ROM.}
  198.  
  199. BEGIN
  200.     IF (tType = ToolTrap) &
  201.         (gMac.machineType > envMachUnknown) &
  202.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  203.         tNumber := BAND(tNumber, $03FF);
  204.         IF tNumber > $01FF THEN                            {which means the tool traps}
  205.             tNumber := _Unimplemented;                    {only go to $01FF}
  206.     END;
  207.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  208.                         GetTrapAddress(_Unimplemented);
  209. END; {TrapAvailable}
  210.  
  211.  
  212. {$S Main}
  213. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  214.  
  215. {Check if a window belongs to a desk accessory.}
  216.  
  217. BEGIN
  218.     IF window = NIL THEN
  219.         IsDAWindow := FALSE
  220.     ELSE    {DA windows have negative windowKinds}
  221.         IsDAWindow := (WindowPeek(window)^.windowKind < 0);
  222. END; {IsDAWindow}
  223.  
  224.  
  225. {$S Main}
  226. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  227.  
  228. {Check to see if a window belongs to the application. If the window pointer
  229.  passed was NIL, then it could not be an application window. WindowKinds
  230.  that are negative belong to the system and windowKinds less than userKind
  231.  are reserved by Apple except for windowKinds equal to dialogKind, which
  232.  mean it is a dialog.
  233.  1.02 - In order to reduce the chance of accidentally treating some window
  234.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  235.  is userKind. If you add different kinds of windows to Sample you'll need
  236.  to change how this all works.}
  237.  
  238. BEGIN
  239.     IF window = NIL THEN
  240.         IsAppWindow := FALSE
  241.     ELSE    {application windows have windowKinds = userKind (8)}
  242.         WITH WindowPeek(window)^ DO
  243.             IsAppWindow := (windowKind = userKind);
  244. END; {IsAppWindow}
  245.  
  246.  
  247. {$S Main}
  248. PROCEDURE AlertUser;
  249.  
  250. {Display an alert that tells the user an error occurred, then exit the program.
  251.  This routine is used as an ultimate bail-out for serious errors that prohibit
  252.  the continuation of the application. Errors that do not require the termination
  253.  of the application should be handled in a different manner. Error checking and
  254.  reporting has a place even in the simplest application. For simplicity, the alert
  255.  displayed here only says that an error occurred, but not what it was. There are
  256.  various methods available for being more specific.}
  257.  
  258. VAR
  259.     itemHit    : INTEGER;
  260. BEGIN
  261.     SetCursor(arrow);
  262.     itemHit := Alert(rUserAlert, NIL);
  263.     ExitToShell;
  264. END; {AlertUser}
  265.  
  266.  
  267. {$S Main}
  268. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  269.  
  270. {Close a window.}
  271.  
  272. {1.01 - At this point, if there was a document associated with a
  273.  window, you could do any document saving processing if it is 'dirty'.
  274.  DoCloseWindow would return TRUE if the window actually closes, i.e.,
  275.  the user does not cancel from a save dialog. This result is handy when
  276.  the user quits an application, but then cancels a save of a document
  277.  associated with a window. We also added code to close the application
  278.  window since otherwise, the termination routines would never stop looping,
  279.  waiting for FrontWindow to return NIL.}
  280.  
  281. BEGIN
  282.     DoCloseWindow := TRUE;
  283.     IF IsDAWindow(window) THEN
  284.         CloseDeskAcc(WindowPeek(window)^.windowKind)
  285.     ELSE IF IsAppWindow(window) THEN
  286.         CloseWindow(window);
  287. END; {DoCloseWindow}
  288.  
  289.  
  290. {$S Initialize}
  291. FUNCTION GoGetRect(rectID: INTEGER; VAR theRect: Rect) : BOOLEAN;
  292.  
  293. {This utility loads the global rectangles that are used by the window
  294.  drawing routines. It shows how the resource manager can be used to hold
  295.  values in a convenient manner. These values are then easily altered without
  296.  having to re-compile the source code. In this particular case, we know
  297.  that this routine is being called at initialization time. Therefore,
  298.  if this returns FALSE, we will assume that the application is in such
  299.  bad shape that we should just exit. Your error handling may differ, but
  300.  the check should still be made.}
  301.  
  302. {1.01 - Changed GoGetRect to return a BOOLEAN that indicates if it was successful
  303.  in getting the rectangle rather than just doing ExitToShell.}
  304.  
  305. TYPE
  306.     RectPtr        = ^Rect;
  307.     RectHnd        = ^RectPtr;
  308. VAR
  309.     resource    : Handle;
  310. BEGIN
  311.     resource := GetResource('RECT', rectID);
  312.     IF resource <> NIL THEN BEGIN
  313.         GoGetRect := TRUE;
  314.         theRect := RectHnd(resource)^^;
  315.         END
  316.     ELSE
  317.         GoGetRect := FALSE;
  318. END; {GoGetRect}
  319.  
  320.  
  321. {$S Initialize}
  322. PROCEDURE Initialize;
  323.  
  324. {Set up the whole world, including global variables, Toolbox managers,
  325.  and menus. We also create our one application window at this time.
  326.  Since window storage is non-relocateable, how and when to allocate space
  327.  for windows is very important so that heap fragmentation does not occur.
  328.  Because Sample has only one window and it is only disposed when the application
  329.  quits, we will allocate its space here, before anything that might be a locked
  330.  relocatable object gets into the heap. This way, we can force its storage to be
  331.  in the lowest memory available in the heap. Window storage can differ widely
  332.  amongst applications depending on how many windows are created and disposed.
  333.  If a failure occurs here, we will consider that the application is in such
  334.  bad shape that we should just exit. Your error handling may differ, but
  335.  the checks should still be made.}
  336.  
  337. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  338.  this module. If an error is detected, instead of merely doing an ExitToShell,
  339.  which leaves the user without much to go on, we call AlertUser, which puts
  340.  up a simple alert that just says an error occurred and then calls ExitToShell.
  341.  In the interests of keeping things simple, the alert does not state the specific
  342.  cause of the error, but a more informative alert would be appropriate for more
  343.  sophisticated applications. Since there is no other cleanup needed at this point
  344.  if an error is detected, this form of error- handling is acceptable. If more
  345.  sophisticated error recovery is needed, a signal mechanism, such as is provided
  346.  by Signals, can be used.}
  347.  
  348. VAR
  349.     menuBar            : Handle;
  350.     window            : WindowPtr;
  351.     ignoreError        : OSErr;
  352.     total, contig    : LongInt;
  353.     ignoreResult    : BOOLEAN;
  354.     event            : EventRecord;
  355.     count            : INTEGER;
  356.  
  357. BEGIN
  358.     gInBackground := FALSE;
  359.  
  360.     InitGraf(@thePort);
  361.     InitFonts;
  362.     InitWindows;
  363.     InitMenus;
  364.     TEInit;
  365.     InitDialogs(NIL);
  366.     InitCursor;
  367.     
  368.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  369.      if you are using it.}
  370.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  371.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  372.      of checking for port availability themselves.}
  373.     
  374.     {This next bit of code is necessary to allow the default button of our
  375.      alert be outlined.
  376.      1.02 - Changed to call EventAvail so that we don't lose some important
  377.      events.}
  378.      
  379.     FOR count := 1 TO 3 DO
  380.         ignoreResult := EventAvail(everyEvent, event);
  381.     
  382.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  383.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  384.      call to SysEnvirons by calling it after initializing AppleTalk.}
  385.      
  386.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  387.     
  388.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  389.     
  390.     IF gMac.machineType < 0 THEN AlertUser;
  391.     
  392.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  393.      in TrapAvailable if a tool trap value is out of range.}
  394.      
  395.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  396.  
  397.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  398.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  399.      MultiFinder we needed. This did not work well because it assumed too much about
  400.      the relationship between what we asked MultiFinder for and what we would actually
  401.      get back, as well as how to measure it. Instead, we will use an alternate
  402.      method comprised of two steps.}
  403.      
  404.     {It is better to first check the size of the application heap against a value
  405.      that you have determined is the smallest heap the application can reasonably
  406.      work in. This number should be derived by examining the size of the heap that
  407.      is actually provided by MultiFinder when the minimum size requested is used.
  408.      The derivation of the minimum size requested from MultiFinder is described
  409.      in Sample.h. The check should be made because the preferred size can end up
  410.      being set smaller than the minimum size by the user. This extra check acts to
  411.      insure that your application is starting from a solid memory foundation.}
  412.      
  413.     IF ORD(GetApplLimit) - ORD(ApplicZone) < kMinHeap THEN AlertUser;
  414.     
  415.     {Next, make sure that enough memory is free for your application to run. It
  416.      is possible for a situation to arise where the heap may have been of required
  417.      size, but a large scrap was loaded which left too little memory. To check for
  418.      this, call PurgeSpace and compare the result with a value that you have determined
  419.      is the minimum amount of free memory your application needs at initialization.
  420.      This number can be derived several different ways. One way that is fairly
  421.      straightforward is to run the application in the minimum size configuration
  422.      as described previously. Call PurgeSpace at initialization and examine the value
  423.      returned. However, you should make sure that this result is not being modified
  424.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  425.      PurgeSpace. Make sure to remove that call before shipping, though.}
  426.      
  427.     PurgeSpace(total, contig);
  428.     IF total < kMinSpace THEN AlertUser;
  429.  
  430.     {The extra benefit to waitng until after the Toolbox Managers have been initialized
  431.      before checking memory is that we can now give the user an alert to tell him what
  432.      happened. Although it is possible that the memory situation could be worsened by
  433.      displaying an alert, MultiFinder would gracefully exit the application with
  434.      an informative alert if memory became critical. Here we are acting more
  435.      in a preventative manner to avoid future disaster from low-memory problems.}
  436.      
  437.     {We will allocate our own window storage instead of letting the Window
  438.      Manager for two reasons. One, GetNewWindow locks the 'WIND' resource
  439.      handle before calling NewWindow and this can lead to heap fragmentation.
  440.      Two, it takes just as much time for NewWindow to get the memory as it
  441.      does for us to get it.}
  442.  
  443.     window := WindowPtr(NewPtr(SIZEOF(WindowRecord)));
  444.     IF window = NIL THEN AlertUser;
  445.     window := GetNewWindow(rWindow, Ptr(window), WindowPtr(-1));
  446.  
  447.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  448.     IF menuBar = NIL THEN AlertUser;
  449.     SetMenuBar(menuBar);                    {install menus}
  450.     DisposHandle(menuBar);
  451.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  452.     DrawMenuBar;
  453.  
  454.     gStopped := TRUE;
  455.     IF NOT GoGetRect(rStopRect, gStopRect) THEN
  456.         AlertUser;                            {the stop light rectangle}
  457.     IF NOT GoGetRect(rGoRect, gGoRect) THEN
  458.         AlertUser;                            {the go light rectangle}
  459. END; {Initialize}
  460.  
  461.  
  462. (**************************************************************************************
  463. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  464.  
  465. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  466.  and not having to worry about updating the windows, but it suffered
  467.  from a fatal flaw. If a desk accessory owned two windows, it would
  468.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  469.  got around to calling DoCloseWindow for that other window that was already
  470.  closed, things would go very poorly. Another option would be to have a
  471.  procedure, GetRearWindow, that would go through the window list and return
  472.  the last window. Instead, we decided to present the standard approach
  473.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  474.  has a potential benefit in that the window whose document needs to be saved
  475.  may be visible since it is the front window, therefore decreasing the
  476.  chance of user confusion. For aesthetic reasons, the windows in the
  477.  application should be checked for updates periodically and have the
  478.  updates serviced.}
  479. **************************************************************************************)
  480.  
  481.  
  482. {$S Main}
  483. PROCEDURE Terminate;
  484.  
  485. {Clean up the application and exits. We close all of the windows so that
  486.  they can update their documents, if any.}
  487.  
  488. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  489.  shell, but will return instead.}
  490.  
  491. VAR
  492.     aWindow    : WindowPtr;
  493.     closed    : BOOLEAN;
  494.  
  495. BEGIN
  496.     closed := TRUE;
  497.     REPEAT
  498.         aWindow := FrontWindow;                    {get the current front window}
  499.         IF aWindow <> NIL THEN
  500.             closed := DoCloseWindow(aWindow);    {close this window}
  501.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  502.     IF closed THEN
  503.         ExitToShell;                            {exit if no cancellation}
  504. END; {Terminate}
  505.  
  506.  
  507. {$S Main}
  508. PROCEDURE SetLight(window: WindowPtr; newStopped: BOOLEAN);
  509.  
  510. {Change the setting of the light.}
  511.  
  512. BEGIN
  513.     IF newStopped <> gStopped THEN BEGIN
  514.         gStopped := newStopped;
  515.         SetPort(window);
  516.         InvalRect(window^.portRect);
  517.     END;
  518. END; {SetLight}
  519.  
  520.  
  521. {$S Main}
  522. PROCEDURE AdjustMenus;
  523.  
  524. {Enable and disable menus based on the current state.
  525.  The user can only select enabled menu items. We set up all the menu items
  526.  before calling MenuSelect or MenuKey, since these are the only times that
  527.  a menu item can be selected. Note that MenuSelect is also the only time
  528.  the user will see menu items. This approach to deciding what enable/
  529.  disable state a menu item has the advantage of concentrating all the decision-
  530.  making in one routine, as opposed to being spread throughout the application.
  531.  Other application designs may take a different approach that may or may not be
  532.  just as valid.}
  533.  
  534. VAR
  535.     window            : WindowPtr;
  536.     menu            : MenuHandle;
  537.  
  538. BEGIN
  539.     window := FrontWindow;
  540.  
  541.     menu := GetMHandle(mFile);
  542.     IF IsDAWindow(window) THEN                {we can allow desk accessories to be closed from the menu}
  543.         EnableItem(menu, iClose)
  544.     ELSE
  545.         DisableItem(menu, iClose);            {but not our traffic light window}
  546.  
  547.     menu := GetMHandle(mEdit);
  548.     IF IsDAWindow(window) THEN BEGIN        {a desk accessory might need the edit menu}
  549.         EnableItem(menu, iUndo);
  550.         EnableItem(menu, iCut);
  551.         EnableItem(menu, iCopy);
  552.         EnableItem(menu, iPaste);
  553.         EnableItem(menu, iClear);
  554.     END ELSE BEGIN                            {but we know we do not}
  555.         DisableItem(menu, iUndo);
  556.         DisableItem(menu, iCut);
  557.         DisableItem(menu, iCopy);
  558.         DisableItem(menu, iClear);
  559.         DisableItem(menu, iPaste);
  560.     END;
  561.  
  562.     menu := GetMHandle(mLight);
  563.     IF IsAppWindow(window) THEN BEGIN        {we know that it must be the traffic light}
  564.         EnableItem(menu, iStop);
  565.         EnableItem(menu, iGo);
  566.     END ELSE BEGIN
  567.         DisableItem(menu, iStop);
  568.         DisableItem(menu, iGo);
  569.     END;
  570.     CheckItem(menu, iStop, gStopped);        {we can also determine check/uncheck state, too}
  571.     CheckItem(menu, iGo, NOT gStopped);
  572. END; {AdjustMenus}
  573.  
  574.  
  575. {$S Main}
  576. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  577.  
  578. {This is called when an item is chosen from the menu bar (after calling
  579.  MenuSelect or MenuKey). It performs the right operation for each command.
  580.  It is good to have both the result of MenuSelect and MenuKey go to
  581.  one routine like this to keep everything organized.}
  582.  
  583. VAR
  584.     menuID            : INTEGER;        {the resource ID of the selected menu}
  585.     menuItem        : INTEGER;        {the item number of the selected menu}
  586.     itemHit            : INTEGER;
  587.     daName            : Str255;
  588.     daRefNum        : INTEGER;
  589.     handledByDA        : BOOLEAN;
  590.     ignore            : BOOLEAN;
  591.  
  592. BEGIN
  593.     menuID := HiWrd(menuResult);    {use built-ins (for efficiency)...}
  594.     menuItem := LoWrd(menuResult);    {to get menu item number and menu number}
  595.     CASE menuID OF
  596.         mApple:
  597.             CASE menuItem OF
  598.                 iAbout:                {bring up alert for About}
  599.                     itemHit := Alert(rAboutAlert, NIL);
  600.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  601.                     GetItem(GetMHandle(mApple), menuItem, daName);
  602.                     daRefNum := OpenDeskAcc(daName);
  603.                 END;
  604.             END;
  605.         mFile:
  606.             CASE menuItem OF
  607.                 iClose:
  608.                     ignore := DoCloseWindow(FrontWindow); {we don't care if cancelled}
  609.                 iQuit:
  610.                     Terminate;
  611.             END;
  612.         mEdit:                        {call SystemEdit for DA editing & MultiFinder}
  613.             handledByDA := SystemEdit(menuItem-1);    {since we don't do any editing}
  614.         mLight:
  615.             CASE menuItem OF
  616.                 iStop:
  617.                     SetLight(FrontWindow, TRUE);
  618.                 iGo:
  619.                     SetLight(FrontWindow, FALSE);
  620.             END;
  621.     END;
  622.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  623. END; {DoMenuCommand}
  624.  
  625.  
  626. {$S Main}
  627. PROCEDURE DrawWindow(window: WindowPtr);
  628.  
  629. {Draw the contents of the application window. We do some drawing in color, using
  630.  Classic QuickDraw's color capabilities. This will be black and white on old
  631.  machines, but color on color machines. At this point, the window's visRgn is
  632.  set to allow drawing only where it needs to be done.}
  633.  
  634. BEGIN
  635.     SetPort(window);
  636.  
  637.     EraseRect(window^.portRect);    {clear out any garbage that might be left behind}
  638.     IF gStopped THEN                {draw a red (or white) stop light}
  639.         ForeColor(redColor)
  640.     ELSE
  641.         ForeColor(whiteColor);
  642.     PaintOval(gStopRect);
  643.     ForeColor(blackColor);
  644.     FrameOval(gStopRect);
  645.     IF NOT gStopped THEN            {draw a green (or white) go light}
  646.         ForeColor(greenColor)
  647.     ELSE
  648.         ForeColor(whiteColor);
  649.     PaintOval(gGoRect);
  650.     ForeColor(blackColor);
  651.     FrameOval(gGoRect);
  652. END; {DrawWindow}
  653.  
  654.  
  655. {$S Main}
  656. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  657.  
  658. {This is called when a mouse-down event occurs in the content of a window.
  659.  Other applications might want to call FindControl, TEClick, etc., to
  660.  further process the click.}
  661.  
  662. BEGIN
  663.     SetLight(window, NOT gStopped);
  664. END; {DoContentClick}
  665.  
  666.  
  667. {$S Main}
  668. PROCEDURE DoUpdate(window: WindowPtr);
  669.  
  670. {This is called when an update event is received for a window.
  671.  It calls DrawWindow to draw the contents of an application window.
  672.  As an effeciency measure that does not have to be followed, it
  673.  calls the drawing routine only if the visRgn is non-empty. This
  674.  will handle situations where calculations for drawing or drawing
  675.  itself is very time-consuming.}
  676.  
  677. BEGIN
  678.     IF IsAppWindow(window) THEN BEGIN
  679.         BeginUpdate(window);                    {sets up the visRgn, clears updateRgn}
  680.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  681.             DrawWindow(window);
  682.         EndUpdate(window);                        {restores the visRgn}
  683.     END;
  684. END; {DoUpdate}
  685.  
  686.  
  687. {$S Main}
  688. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  689.  
  690. {This is called when a window is activated or deactivated.
  691.  In Sample, the Window Manager's handling of activate and
  692.  deactivate events is sufficient. Other applications may have
  693.  TextEdit records, controls, lists, etc., to activate/deactivate.}
  694.  
  695. BEGIN
  696.     IF IsAppWindow(window) THEN
  697.         IF becomingActive THEN
  698.             {do whatever you need to at activation}
  699.         ELSE
  700.             {do whatever you need to at deactivation};
  701. END; {DoActivate}
  702.  
  703.  
  704. {$S Main}
  705. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  706.  
  707. {Get the global coordinates of the mouse. When you call OSEventAvail
  708.  it will return either a pending event or a null event. In either case,
  709.  the where field of the event record will contain the current position
  710.  of the mouse in global coordinates and the modifiers field will reflect
  711.  the current state of the modifiers. Another way to get the global
  712.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  713.  being sure that thePort is set to a valid port.}
  714.  
  715. VAR
  716.     event    : EventRecord;
  717.     
  718. BEGIN
  719.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  720.     mouse := event.where;                    {just the mouse position}
  721. END;
  722.  
  723.  
  724. {$S Main}
  725. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  726.  
  727. {Change the cursor's shape, depending on its position. This also calculates the region
  728.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  729.  that region, an event is generated, causing this routine to be called. This
  730.  allows us to change the region to the region the mouse is currently in. If
  731.  there is more to the event than just “the mouse moved”, we get called before the
  732.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  733.  this is called again before we fall back into WNE.}
  734.  
  735.  
  736. VAR
  737.     window                : WindowPtr;
  738.     arrowRgn            : RgnHandle;
  739.     plusRgn                : RgnHandle;
  740.     globalPortRect        : Rect;
  741.     
  742.  
  743. BEGIN
  744.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  745.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  746.         {calculate regions for different cursor shapes}
  747.         arrowRgn := NewRgn;
  748.         plusRgn := NewRgn;
  749.  
  750.         {start with a big, big rectangular region}
  751.         {1.01 - changed to kExtremeNeg and kExtremePos for consistency}
  752.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg,
  753.                             kExtremePos, kExtremePos);
  754.  
  755.         {calculate plusRgn}
  756.         IF IsAppWindow(window) THEN BEGIN
  757.             SetPort(window);            {make a global version of the portRect}
  758.             SetOrigin(-window^.portBits.bounds.left, -window^.portBits.bounds.top);
  759.             globalPortRect := window^.portRect;
  760.             RectRgn(plusRgn, globalPortRect);
  761.             SectRgn(plusRgn, window^.visRgn, plusRgn);
  762.             SetOrigin(0, 0);
  763.         END;
  764.  
  765.         {subtract other regions from arrowRgn}
  766.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  767.  
  768.         {change the cursor and the region parameter}
  769.         IF PtInRgn(mouse, plusRgn) THEN BEGIN
  770.             SetCursor(GetCursor(plusCursor)^^);
  771.             CopyRgn(plusRgn, region);
  772.         END ELSE BEGIN
  773.             SetCursor(arrow);
  774.             CopyRgn(arrowRgn, region);
  775.         END;
  776.  
  777.         {get rid of our local regions}
  778.         DisposeRgn(arrowRgn);
  779.         DisposeRgn(plusRgn);
  780.     END;
  781. END; {AdjustCursor}
  782.  
  783.  
  784. {$S Main}
  785. PROCEDURE DoEvent(event: EventRecord);
  786.  
  787. {Do the right thing for an event. Determine what kind of event it is, and call
  788.  the appropriate routines.}
  789.  
  790. VAR
  791.     part, err    : INTEGER;
  792.     window        : WindowPtr;
  793.     hit            : BOOLEAN;
  794.     key            : CHAR;
  795.     aPoint        : Point;
  796.  
  797. BEGIN
  798.     CASE event.what OF
  799.         mouseDown: BEGIN
  800.             part := FindWindow(event.where, window);
  801.             CASE part OF
  802.                 inMenuBar: BEGIN            {process the menu command}
  803.                     AdjustMenus;
  804.                     DoMenuCommand(MenuSelect(event.where));
  805.                 END;
  806.                 inSysWindow:                {let the system handle the mouseDown}
  807.                     SystemClick(event, window);
  808.                 inContent:
  809.                     IF window <> FrontWindow THEN BEGIN
  810.                         SelectWindow(window);
  811.                         {DoEvent(event);}    {use this line for "do first click"}
  812.                     END ELSE
  813.                         DoContentClick(window, event);
  814.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  815.                     DragWindow(window, event.where, screenBits.bounds);
  816.                 inGrow:;
  817.                 inZoomIn, inZoomOut:;
  818.             END;
  819.         END;
  820.         keyDown, autoKey: BEGIN                {check for menukey equivalents}
  821.             key := CHR(BAnd(event.message, charCodeMask));
  822.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN    {Command key down}
  823.                 IF event.what = keyDown THEN BEGIN
  824.                     AdjustMenus;            {enable/disable/check menu items properly}
  825.                     DoMenuCommand(MenuKey(key));
  826.                 END;
  827.         END;                                {call DoActivate with the window and...}
  828.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  829.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  830.         updateEvt:                          {call DoUpdate with the window to update}
  831.             DoUpdate(WindowPtr(event.message));
  832.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  833.          to a diskEvt, so that the user can format a floppy.}
  834.         diskEvt:
  835.             IF HiWrd(event.message) <> noErr THEN BEGIN
  836.                 SetPt(aPoint, kDILeft, kDITop);
  837.                 err := DIBadMount(aPoint, event.message);
  838.             END;
  839.         kOSEvent:
  840.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  841.                 kSuspendResumeMessage: BEGIN
  842.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  843.                     DoActivate(FrontWindow, NOT gInBackground);
  844.                 END;
  845.             END;
  846.     END;
  847. END; {DoEvent}
  848.  
  849.  
  850. {$S Main}
  851. PROCEDURE EventLoop;
  852.  
  853. {Get events forever, and handle them by calling DoEvent.
  854.  Get the events by calling WaitNextEvent, if it's available, otherwise
  855.  by calling GetNextEvent. Also call AdjustCursor each time through the loop.}
  856.  
  857. VAR
  858.     cursorRgn    : RgnHandle;
  859.     gotEvent    : BOOLEAN;
  860.     event        : EventRecord;
  861.     mouse        : Point;
  862.  
  863. BEGIN
  864.     cursorRgn := NewRgn;                {we’ll pass WNE an empty region the 1st time thru}
  865.     REPEAT
  866.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  867.             GetGlobalMouse(mouse);        {since we might go to sleep}
  868.             AdjustCursor(mouse, cursorRgn);
  869.             gotEvent := WaitNextEvent(everyEvent, event, MAXLONGINT, cursorRgn);
  870.         END ELSE BEGIN
  871.             SystemTask;                    {must be called if using GetNextEvent}
  872.             gotEvent := GetNextEvent(everyEvent, event);
  873.         END;
  874.         IF gotEvent THEN BEGIN
  875.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  876.             DoEvent(event);
  877.         END;
  878.         {If you are using modeless dialogs that have editText items,
  879.          you will want to call IsDialogEvent to give the caret a chance
  880.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  881.          for a non-NIL value before calling IsDialogEvent.}
  882.     UNTIL FALSE;                        {loop forever; we quit through an ExitToShell}
  883. END; {EventLoop}
  884.  
  885.  
  886. PROCEDURE _DataInit; EXTERNAL;
  887.  
  888. {This routine is part of the MPW runtime library. This external
  889.  reference to it is done so that we can unload its segment, %A5Init.}
  890.  
  891. {$S Main}
  892. BEGIN
  893.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  894.     
  895.     {1.01 - call to ForceEnvirons removed}
  896.     {If you have stack requirements that differ from the default,
  897.      then you could use SetApplLimit to increase StackSpace at 
  898.      this point, before calling MaxApplZone.}
  899.      
  900.     MaxApplZone;            {expand the heap so code segments load at the top}
  901.  
  902.     Initialize;                {initialize the program}
  903.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  904.  
  905.     EventLoop;                {call the main event loop}
  906. END.
  907.